package gui.gui2d.lan;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.plaf.basic.BasicTabbedPaneUI.TabSelectionHandler;
import javax.swing.table.TableColumnModel;

import utility.NameMemmory;
import multiplayer.lan.ServerInfo;
import multiplayer.lan.ServersOnAir;

public class LanServersManagerPanel extends JPanel implements Observer{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	String[] columnNames = {"Indirizzo ip" , "Nick"};

	private static final int TOP_SIZE = 50;
	private static final int BOTTOM_SIZE = 50;
	private static final int LEFT_SIZE = 50;
	private static final int RIGHT_SIZE = 500;
	private DefaultListModel<String> m= new DefaultListModel<String>();
	private JList<String> ip= new JList<String>(m);

	JTable jt = new JTable();
	private OurTableModel otm= new OurTableModel();
	private MouseAdapter ma;

	private JPanel top=new JPanel();
	private JPanel bottom=new JPanel();
	private JPanel left=new JPanel();
	private JPanel right=new JPanel();
	private JPanel center=new JPanel();

	private JPanel infoPanel = new JPanel();
	private JLabel info=new JLabel(" ");
	private boolean endWait=false;


	JTextField ipField=new JTextField(15);
	JTextField nameField = new JTextField(15);

	JButton connectButton= new JButton("Connetti");
	JLabel jl = new JLabel("                  Indietro"); 
	public LanServersManagerPanel() {
		//this.add(ip);
		loadGui();
	}

	public void loadGui(){
		this.setLayout(new BorderLayout());
		this.add(top , BorderLayout.NORTH);
		this.add(bottom, BorderLayout.SOUTH);
		this.add(left, BorderLayout.WEST);
		this.add(right, BorderLayout.EAST);
		this.add(center, BorderLayout.CENTER);
		top.setPreferredSize(new Dimension(0,TOP_SIZE));
		bottom.setPreferredSize(new Dimension(0,BOTTOM_SIZE));
		left.setPreferredSize(new Dimension(LEFT_SIZE,0));
		right.setPreferredSize(new Dimension(RIGHT_SIZE,0));
		center.setLayout(new BorderLayout());
		JScrollPane jsPane= new JScrollPane(jt);
		jsPane.setOpaque(false);
		jsPane.getViewport().setOpaque(false);
		jt.setModel(otm);
		jt.setOpaque(false);
		String carattere = "TimesRoman";
		int plain = Font.ITALIC;
		int dimensioni = 20;
		Font font = new Font(carattere, plain, dimensioni);
		jt.setFont(font);
		jt.getTableHeader().setFont(font);
		jt.getTableHeader().setOpaque(false);
		jt.setRowHeight(30);
		center.add(jsPane, BorderLayout.CENTER);
		this.setOpaque(false);
		top.setOpaque(false);
		bottom.setOpaque(false);
		left.setOpaque(false);
		right.setOpaque(false);
		center.setOpaque(false);
		loadLateralMenu();
		//		jt.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
		//	        public void valueChanged(ListSelectionEvent event) {
		//	            // do some actions here, for example
		//	            // print first column value from selected row
		//	            System.out.println(jt.getValueAt(jt.getSelectedRow(), 0).toString());
		//	        }
		//	    });
		jt.addMouseListener(new MouseListener() {

			@Override
			public void mouseReleased(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mousePressed(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseExited(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseClicked(MouseEvent arg0) {
				ipField.setText(jt.getValueAt(jt.getSelectedRow(), 0).toString());

			}
		});
	}

	private void loadLateralMenu() {
		right.setLayout(new BoxLayout(right, BoxLayout.PAGE_AXIS));

		JLabel ipLabel= new JLabel(" Indirizzo ip server:");
		JLabel nameLabel= new JLabel(" Il tuo Nickname:");
		String carattere = "TimesRoman";
		int plain = Font.ITALIC;
		int dimensioni = 35;
		Font font = new Font(carattere, plain, dimensioni);
		ipLabel.setFont(font);
		ipLabel.setForeground(Color.WHITE);
		nameLabel.setFont(font);
		nameLabel.setForeground(Color.WHITE);


		nameField.setText(NameMemmory.getInstace().getName());
		int dimensioni1 = 28;
		Font font1 = new Font(carattere, plain, dimensioni1);
		ipField.setFont(font1);
		nameField.setFont(font1);
		JPanel ipPanelLabel= new JPanel();
		ipPanelLabel.setOpaque(false);
		JPanel ipPanelField= new JPanel();
		ipPanelField.setOpaque(false);
		JPanel namePanelLabel= new JPanel();
		namePanelLabel.setOpaque(false);
		JPanel namePanelField= new JPanel();
		namePanelField.setOpaque(false);
		JPanel buttonConnectionPanel= new JPanel();

		JPanel spessor=new JPanel();
		spessor.setPreferredSize(new Dimension(0,100));
		JPanel backToMenuPanel = new JPanel();
		backToMenuPanel.setLayout(new GridLayout(1,0));
		backToMenuPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
		

		jl.setFont(font);
		jl.setForeground(Color.white);
		backToMenuPanel.add(jl);
		spessor.setOpaque(false);
		backToMenuPanel.setOpaque(false);

		info.setFont(font1);
		info.setForeground(Color.RED);
		infoPanel.add(info);
		infoPanel.setOpaque(false);
		connectButton.setFont(font1);
		connectButton.setOpaque(false);
		connectButton.setPreferredSize(new Dimension(150,40));
		buttonConnectionPanel.add(connectButton);
		buttonConnectionPanel.setOpaque(false);
		buttonConnectionPanel.setBorder(BorderFactory.createEmptyBorder(40, 10, 10, 10));

		right.add(backToMenuPanel); 
		right.add(spessor);
		right.add(ipPanelLabel);
		right.add(ipPanelField);
		right.add(namePanelLabel);
		right.add(namePanelField);
		right.add(buttonConnectionPanel);
		right.add(infoPanel);
		ipPanelLabel.add(ipLabel);
		ipPanelField.add(ipField);
		namePanelField.add(nameField);
		namePanelLabel.add(nameLabel);
		JPanel fixSize = new JPanel();
		fixSize.setOpaque(false);
		fixSize.setPreferredSize(new Dimension(0,790));
		right.add(fixSize);
	}

	public void addButtonConnectionListener(ActionListener l){
		connectButton.addActionListener(l);
	}
	public String getIpFieldValue(){
		return ipField.getText();
	}
	public String getNameFieldValue(){
		return nameField.getText();
	}

	public void infoOnConnection(){
		infoPanel.add(info);
		info.setForeground(Color.WHITE);
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				while(!endWait){
					info.setText("Connessione in corso.   ");
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(endWait){
						continue;
					}
					info.setText("Connessione in corso..  ");

					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(endWait){
						continue;
					}
					info.setText("Connessione in corso... ");
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(endWait){
						continue;
					}
					info.setText("Connessione in corso....");
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				infoPanel.removeAll();

			}
		});
		t.start();
	}

	public void setEndWait(boolean endWait) {
		this.endWait = endWait;

	}

	public void infoRemoveAll(){
		info.setText(" ");

	}

	public void insertInfo(final String s){
		info.setForeground(Color.RED);
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				for(int i = 0 ;i<2 ; i++){

					info.setText(s);
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					info.setText(" ");
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
				infoRemoveAll();
			}
		});
		t.start();


	}

	public void insertInfoNoError(final String s){
		Thread t = new Thread(new Runnable() {

			@Override
			public void run() {
				info.setForeground(Color.WHITE);
				info.setText(s);
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				info.setText(" ");
			}
		});
		t.start();


	}




	@Override
	public void update(Observable o, Object arg) {
		if(o instanceof ServersOnAir){
			if(arg instanceof ServersOnAir ){
				ServersOnAir soa= (ServersOnAir) arg;
				loadServers(soa.getServers());
			}
		}
		if(o instanceof ServersOnAir){
			if(arg instanceof String){
				String ip = (String) arg;
				removeServer(ip);
			}
		}
	}

	public void loadServers(HashMap<String, ServerInfo> hashMap){
		Iterator<String> it = hashMap.keySet().iterator();
		while(it.hasNext()){
			String ip = it.next();
			addServer(ip,hashMap.get(ip));
		}
		jt.revalidate();
	}


	public void addServer(String ip, ServerInfo si){
		otm.addValue(ip+":"+si.getPort(), si.getNome());
	}
	public void removeServer(String ip){
		otm.removeValue(ip);
		jt.revalidate();
	}

	public void loadMouseAdapter(MouseAdapter ma){
		this.ma=ma;
		ip.addMouseListener(this.ma);
	}

	public static void main(String[] args) {
		JFrame jf= new JFrame();
		jf.setSize(new Dimension(1280, 720));
		LanServersManagerPanel lsmp= new LanServersManagerPanel();	
		jf.add(lsmp);
		jf.setVisible(true);
	}
	public void disableButton(){
		connectButton.setEnabled(false);
	}
	public void enableButton(){
		connectButton.setEnabled(true);
	}

	public void addButtonBackListener(MouseListener ml) {
		jl.addMouseListener(ml);
		
	}

}
